package com.macaline.concurrent.rateLimiter;


import cn.hutool.core.util.RuntimeUtil;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.concurrent.TimeUnit;

/**
 * 限流工具
 */
public class RateLimiterDemo {



    public static void main(String[] args) throws InterruptedException {
        tryAcquire();
    }

    /**
     * 限流
     */
    public static void tryAcquire() throws InterruptedException {
        final RateLimiter rateLimiter = RateLimiter.create(1); // 表示每秒产生的令牌数
//        TimeUnit.SECONDS.sleep(10);
        for (int i = 0; i < 10; i++) {
            boolean b = rateLimiter.tryAcquire(1, TimeUnit.SECONDS);
            if(b){
                System.out.println("执行下标：" + i);
            }else {
                System.out.println("抛弃下标：" + i);
            }
        }
    }

    /**
     * 限流
     */
    public static void acquire() throws InterruptedException {
        final RateLimiter rateLimiter = RateLimiter.create(1); // 表示每秒产生的令牌数
//        TimeUnit.SECONDS.sleep(10);
        for (int i = 0; i < 10; i++) {
            rateLimiter.acquire();
            System.out.println("执行下标：" + i);
        }
    }


}
